package com.beizhen.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.beizhen.demo.entity.Code;
import com.beizhen.demo.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin  //跨域支持
public class emailController {
    @Autowired
    private CodeService codeService;
    //发送普通文本邮件
    @RequestMapping(value = "/sendMail")
    @ResponseBody
    public void sendMail(@RequestParam("email") String email, Model model) {
        String code = UUID.randomUUID().toString().substring(0, 4);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("q2323212340@163.com"); //发送者
        message.setTo(email);  //接受者
        message.setCc("q2323212340@163.com"); //抄送，填发送者的邮箱即可
        message.setSubject("【研学管理】您的验证码通知");	//主题
        message.setText("当前验证码为"+code+"请勿泄露给他人");	//内容
        try {
            /*  javaMailSender.send(message);*/
            System.out.println("简单邮件已经发送");
            System.out.println("ecode"+code);
            Code codes=new Code();
            codes.setPhone(email);
            codes.setCode(code);
            codeService.insertInfo(codes);
        } catch (Exception e) {
            System.out.println("发送简单邮件时发生异常！"+e.toString());
        }
        model.addAttribute("msg", "");

    }


    @GetMapping("doveremail")
    @ResponseBody
    public String verificat(@RequestParam(value = "email") String email,
                            @RequestParam(value = "verification") String verification
    ){
        Map<String,String> jsonmap=new HashMap<>();
        System.out.println("tt"+email);
        String code = codeService.getCode(email);
        if (code.equals(verification)) {
            jsonmap.put("result","ok");
        } else {
            jsonmap.put("result","fail");
        }
        System.out.println("jj"+jsonmap);
        return JSONArray.toJSONString(jsonmap);
    }

}